package fafmessenger_server.control;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import fafmessenger_server.entity.Message;
import fafmessenger_server.entity.Response;
import fafmessenger_server.entity.User;
import fafmessenger_server.mapper.Users;

public class Controller {
	
	private Users users;
	
	public Controller() {
		users = new Users();
	}
	
	public Response register(String mobilenumber) {
		Response returnvalue = null;
		
		User user = users.getByMobilenumber(mobilenumber);
		
		if (user == null) {
			user = new User(mobilenumber);
			boolean result = users.insert(user);
			
			if (result) {
				returnvalue = new Response(110, true, "User has been succesfully registered.");
			} else {
				returnvalue = new Response(310, false, "Failed to register user. Try again later.");
			}
			
		} else {
			returnvalue = new Response(210, true, "User is already registered.");
		}
		
		return returnvalue;
	}
	
	public Object getMessages(String mobilenumber, String timestamp) {
		Object returnvalue = null;
		
		User user = users.getByMobilenumber(mobilenumber);
		
		if (user != null) {
			ArrayList<Message> messages = new ArrayList<Message>();
			
			for (Message m : user.messages) {
				if (m.getTimestamp().after(Timestamp.valueOf(timestamp))) {
					messages.add(m);
					
					user.messages.delete(m);
				}				
			}
			
			returnvalue = messages;
			
		} else {
			returnvalue = new Response(330, true, "User is not registered.");
		}
		
		return returnvalue;
	}
	
	public Response sendMessage(String fromMobilenumber, String toMobilenumber, String body) {
		Response returnvalue = null;
		
		User toUser = users.getByMobilenumber(toMobilenumber);
		
		if (toUser != null) {
			Date now = new Date();
			Message message = new Message(new Timestamp(now.getTime()), body, fromMobilenumber, toMobilenumber);
			boolean result = toUser.messages.insert(message);
			
			if (result) {
				returnvalue = new Response(120, true, "Message has been succesfully sent.");
			} else {
				returnvalue = new Response(321, false, "Failed to send message. Try again later.");
			}
			
		} else {
			returnvalue = new Response(320, false, "Receipent is not registered.");
		}
		
		return returnvalue;
	}
}
